const Koa = require("koa");
const app = new Koa();
const router = require("./router");
const bodyParser = require("koa-bodyparser");
const cors = require("koa-cors");
const logger = require("koa-logger");
const jwt = require("jsonwebtoken");
const koaJwt = require("koa-jwt");
const path = require("path");
const { koaBody } = require("koa-body");
const serve = require("koa-static");

const { secret } = require("./config");
const { createOrUpdateTable } = require("./config/create");

// 用户
createOrUpdateTable("users", {
  phone: "string",
  nickname: "string",
  password: "string",
  roleType: "integer",
  avatarUrl: "string",
});

// 题目
createOrUpdateTable("questions", {
  type: "string",
  difficulty: "string",
  tags: "string",
  question: "string",
  options: "string",
  answer: "text",
  analysis: "text",
  description: "text",
});

// 保存题目的标签信息
createOrUpdateTable("tags", {
  tagName: "string",
});

// 试卷
createOrUpdateTable("papers", {
  paperName: "string",
  paperContent: "text",
  categories: "string",
  rules: "string",
  isOpen: "string",
});

// 分类
createOrUpdateTable("categories", {
  categoryName: "string",
});

// 考试管理
createOrUpdateTable("exams", {
  paperID: "string",
  examName: "string",
  startTime: "bigInteger",
  endTime: "bigInteger",
  userIDs: "string",
});

// 考生管理
createOrUpdateTable("candidates", {
  examId: "string",
  answerDetailId: "string",
  phone: "string",
  isPass: "string",
  name: "string",
});

// 保存用户答题详情
createOrUpdateTable("answer_details", {
  userID: "string",
  examID: "string",
  userAswers: "string",
  socre: "integer"
});

// 保存用户答案记录
createOrUpdateTable("answers", {
  userID: "string",
  questionID: "string",
  userSelectAnswer: "string",
  socre: "integer",
  isRight: "string",
});

// 文章管理
createOrUpdateTable("posts", {
  userID: "string",
  title: "string",
  content: "text",
  tags: "string",
});

// 帖子
createOrUpdateTable("forums", {
  userID: "string",
  title: "string",
  content: "text",
  categories: "string",
});

// 评论
createOrUpdateTable("comments", {
  forumID: "string",
  userID: "string",
  content: "text",
});

// 使用 koa-jwt 中间件验证 JWT
app.use(
  koaJwt({ secret }).unless({
    path: [
      /^\/public/,
      /^\/api\/user\/login/,
      /^\/api\/user\/register/,
      /^\/api\/user\/captcha/,
      /^\//,
    ],
  })
);

app.use(serve(path.join(__dirname, "public")));

app.use(
  koaBody({
    multipart: true, // 允许接收 multipart/form-data 类型的数据
    formidable: {
      uploadDir: path.join(__dirname, "/public"), // 上传文件保存的目录
      keepExtensions: true, // 保留文件扩展名
    },
  })
);

app.use(cors());
app.use(bodyParser());

app.use(logger());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000, () => {
  console.log("Server started on port 3000");
});
